const express = require("express");
const router = express.Router();
const { db, genid } = require("../db/DbUtils");
const { jwtCheak } = require("../utils/jwt");

// 查询
/**
 * params
 *  keyWord  关键字  (查询title content)
 *  categoryId 分类id
 *  page  当前页数      默认 1
 *  pageSize 分页大小   默认 10
 * */
router.get("/blog", async (req, res) => {
  let { keyWord = "", categoryId = 0, page = 1, pageSize = 10 } = req.query;
  let whereSqls = [];
  let params = [];
  let whereSqlStr = "";

  if (categoryId != 0) {
    whereSqls.push(" `category_id` = ? ");
    params.push(categoryId);
  }

  if (keyWord) {
    // LIKE  模糊查询
    whereSqls.push(" (`title` LIKE ? OR `content` LIKE ?) ");
    params.push(`%${keyWord}%`, `%${keyWord}%`);
  }

  if (whereSqls.length > 0) {
    whereSqlStr = " WHERE " + whereSqls.join(" AND ");
  }

  //   查分页数据
  const search_sql =
    " SELECT `id`,`category_id`,`create_time`,`title`,substr(`content`,0,200) AS `content` FROM `blog` " +
    whereSqlStr +
    " ORDER BY `create_time` DESC LIMIT ?,? ";
  let searchSqlParmas = params.concat([(page - 1) * pageSize, pageSize]);

  // 查数据总数
  let searchCount_sql = " SELECT count(*) as count FROM `blog` " + whereSqlStr;
  let searchCountParams = params;

  let searchRes = await db.async.all(search_sql, searchSqlParmas);
  let countRes = await db.async.all(searchCount_sql, searchCountParams);
  if (!searchRes.err && !countRes.err) {
    res.send({
      code: 200,
      msg: "查询成功",
      data: {
        list: searchRes.rows,
        page: {
          total: countRes.rows[0].count,
          page_size: pageSize,
          curPage: page,
        },
      },
    });
  } else {
    res.send({
      code: 500,
      msg: "查询失败",
    });
  }
});

// 通过id 查询博客
router.get("/detail", async (req, res) => {
  let id = req.query.id;
  if (!id) {
    res.send({
      code: 500,
      msg: "请传入合法的参数",
    });
    return;
  }
  const search_sql = "SELECT * FROM `blog` WHERE `id` = ?";
  let { err, rows } = await db.async.all(search_sql, [id]);
  if (!err) {
    res.send({
      code: 200,
      msg: "查询成功",
      data: rows[0],
    });
  } else {
    res.send({
      code: 500,
      msg: "查询失败",
    });
  }
});

// 添加
/**
 * params
 *   title  标题
 *   categoryId 分类id
 *   content 文本内容
 *  */
router.post("/blog", jwtCheak, async (req, res) => {
  let { title, categoryId, content } = req.body;
  let id = genid.NextId();
  let create_time = new Date().getTime();
  const insert_sql =
    "INSERT INTO `blog` (`id`, `category_id`, `title`, `content`, `create_time`) VALUES (?,?,?, ?,?)";
  let params = [id, categoryId, title, content, create_time];
  let { err, rows } = await db.async.run(insert_sql, params);
  if (!err) {
    res.send({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "添加失败",
    });
  }
});

// 修改
/**
 * params
 *   id   博客id
 *   title 标题
 *   categoryId 分类id
 *   content 文本内容
 *  */
router.put("/blog", jwtCheak, async (req, res) => {
  let { id, title, categoryId, content } = req.body;
  const update_sql =
    "UPDATE `blog` SET `title` = ?, `content` = ?, `category_id` = ? WHERE `id` = ?";
  let params = [title, content, categoryId, id];
  let { err, rows } = await db.async.run(update_sql, params);
  if (!err) {
    res.send({
      code: 200,
      msg: "修改成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "修改失败",
    });
  }
});

// 删除  /category?id=xxx
/**
 * params
 *   id   要删除分类的id
 *  */
router.delete("/blog", jwtCheak, async (req, res) => {
  let id = req.query.id;
  const delete_sql = "DELETE FROM `blog` WHERE `id` = ?";
  let { err, rows } = await db.async.run(delete_sql, [id]);
  if (!err) {
    res.send({
      code: 200,
      msg: "删除成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "删除失败",
    });
  }
});

module.exports = router;
